package com.xiaochong.tir.apiservice.component;

import com.alibaba.fastjson.JSON;
import com.xc.logclient.utils.LogTrace;
import com.xiaochong.tir.apiservice.component.hbase.CurrencyInfoHbaseComponent;
import com.xiaochong.service.common.config.redis.RedisServer;
import com.xiaochong.tir.apiservice.service.ConceptCategoryService;
import com.xiaochong.tir.apiservice.service.CurrencyInfoService;
import com.xiaochong.tir.common.data.hbasepo.CmcCurrencyInfo;
import com.xiaochong.tir.common.data.hbasepo.CurrentcyHighOrLow;
import com.xiaochong.tir.common.data.hbasepo.DailyConceptualIndexInfo;
import com.xiaochong.tir.common.data.po.ConceptCategory;
import com.xiaochong.tir.common.data.po.CurrencyInfo;
import com.xiaochong.tir.common.exception.hbase.HbaseCloseExcetion;
import com.xiaochong.tir.common.exception.hbase.HbaseConnectionExcetion;
import com.xiaochong.tir.common.exception.hbase.HbaseGetTableExcetion;
import com.xiaochong.tir.common.util.DateUtils;
import com.xiaochong.tir.common.util.HbaseTableUtils;
import com.xiaochong.tir.common.util.RedisKeysUtils;
import org.apache.avro.data.Json;
import org.apache.commons.lang3.StringUtils;
import org.apache.hadoop.yarn.webapp.hamlet.Hamlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by org on 2018/4/28.
 * 数据计算和插入hbase中
 */
@Component
public class CmcDataCountCalculateComponent {
    @Resource
    private CoinMarketCapDataComponent coinMarketCapDataComponent;
    @Autowired
    private RedisServer redisServer;
    @Autowired
    private CurrencyInfoService currencyInfoService;
    @Autowired
    private ConceptCategoryService conceptCategoryService;
    @Autowired
    private HbaseBaseQueryComponent hbaseBaseQueryComponent;
    @Autowired
    private CurrencyInfoHbaseComponent currencyInfoHbaseComponent;


    /**
     * 计算大盘分析中的涨跌统计
     */
    public CurrentcyHighOrLow HighsAndLowsCountCalculate(List<CmcCurrencyInfo> cmcCurrencyInfos) {
        //String post = null;
        try {
           // post = coinMarketCapDataComponent.ticker("CNY",0);
            //List<CmcCurrencyInfo> cmcCurrencyInfos = JSON.parseArray(post, CmcCurrencyInfo.class);
            //查出需要统计的货币（数据库）
//            List<CurrencyInfo> currencyInfoList = currencyInfoService.selectAllEnableCurrencyList();
//            LogTrace.info("涨跌统计计算","货币总数量",currencyInfoList!=null?String.valueOf(currencyInfoList.size()):"0");
//            //LogTrace.info("涨跌计算统计-百分比计算-已启用的货币列表",JSON.toJSONString(currencyInfoList));
//            Map<String,Object> currencyMap = new HashMap();
//            int AllCount =currencyInfoList.size();
//            for(CurrencyInfo c :currencyInfoList){
//                currencyMap.put(c.getCmcId(),c.getCmcId());
//            }
            int AllCount = cmcCurrencyInfos!=null? cmcCurrencyInfos.size():0;
            LogTrace.info("涨跌统计计算","货币总数量",AllCount+"");
            //统计各个
            int f10=0;// -10以下
            int f10Tof6=0;// -10到-6%以下
            int f6Tof2=0;// -6到-2以下 改成 -6到-4以下
            int f2To0=0;// -2到0以下   改成 -4到-2以下
            int z0Toz2=0;// 0到2以下   改成  -2到0以下
            int z2Toz4=0;// 2到4以下   改成 0到2以下
            int z4Toz6=0;// 4到6以下   改成 2到4以下
            int z6Toz8=0;// 6到8以下   改成 4到6以下
            int z8Toz10=0;// 8到10以下 改成 6到10以下
            int z10=0;// 10以上
            int count11=0;// 计算6%以上
            int count12=0;// 上涨的数量
            int downCount=0;//下跌数量
            String evaluate="";//评语
            String score="";//评分
            for(CmcCurrencyInfo c :cmcCurrencyInfos){
//                if(!currencyMap.containsKey(c.getId())) continue;
                LogTrace.info("计算涨跌统计为统计到的货币","货币id",c.getId());
               // AllCount++; //总笔数 -有效的
                if(c.getPercentChange24h() == null){
                    f10++;downCount++;
                    LogTrace.info("计算涨跌统计为统计到的货币","货币id",c.getId()+"24小时涨幅null");
                    continue;
                }
                double percentChange1h = Double.valueOf(c.getPercentChange24h());
                if(percentChange1h < -10){
                    f10++;downCount++;
                }else if(percentChange1h >= -10 && percentChange1h < -6){
                    f10Tof6++;downCount++;
                }else if(percentChange1h >= -6 && percentChange1h < -4){
                    f6Tof2++;downCount++;
                }else if(percentChange1h >= -4 && percentChange1h < -2){
                    f2To0++;downCount++;
                }else if(percentChange1h >= -2 && percentChange1h < 0){
                   // f2To0++;downCount++;
                    z0Toz2++;downCount++;
                }else if(percentChange1h >= 0 && percentChange1h < 2){
                    //z0Toz2++;count12++;
                    z2Toz4++;count12++;
                }else if(percentChange1h >= 2 && percentChange1h < 4){
                   // z2Toz4++;count12++;
                    z4Toz6++;count12++;
                }else if(percentChange1h >= 4 && percentChange1h < 6){
                   // z4Toz6++;count12++;
                    z6Toz8++;count12++;
                }else if(percentChange1h >= 6 && percentChange1h < 10){
                    z8Toz10++;count11++;count12++;
                }else if(percentChange1h >= 10){
                    z10++;count11++;count12++;
                }else{
                    LogTrace.info("计算涨跌统计为统计到的货币","涨跌幅度"+c.getId(),String.valueOf(percentChange1h));
                }
            }
            //计算评分，给出评语
            BigDecimal highs0 = BigDecimal.valueOf(Double.valueOf(count12)/Double.valueOf(AllCount) *100);
            BigDecimal highs6 = BigDecimal.valueOf(Double.valueOf(count11)/Double.valueOf(AllCount) *100);
            double percent = Double.valueOf(String.valueOf(highs0));
            if(percent < 10){
                score = String.valueOf(1);
                evaluate = "价格普遍下跌";
            }else if(percent >= 10 && percent < 20){
                score = String.valueOf(2);
                evaluate = "价格普遍下跌";
            }else if(percent >= 20 && percent < 30){
                score = String.valueOf(3);
                evaluate = "多数货币价格下跌";
            }else if(percent >= 30 && percent < 40){
                score = String.valueOf(4);
                evaluate = "多数货币价格下跌";
            }else if(percent >= 40 && percent < 50){
                score = String.valueOf(5);
                evaluate = "货币价格涨跌数量均衡";
            }else if(percent >= 50 && percent < 60){
                score = String.valueOf(6);
                evaluate = "货币价格涨跌数量均衡";
            }else if(percent >= 60 && percent < 70){
                score = String.valueOf(7);
                evaluate = "多数货币价格上涨";
            }else if(percent >= 70 && percent < 80){
                score = String.valueOf(8);
                evaluate = "多数货币价格上涨";
            }else if(percent >= 80 && percent < 90){
                score = String.valueOf(9);
                evaluate = "价格普遍上涨";
            }else{
                score = String.valueOf(10);
                evaluate = "价格普遍上涨";
            }
            /*if(Double.valueOf(String.valueOf(highs0))<45){
                if(Double.valueOf(String.valueOf(highs6)) < 5){
                    score = String.valueOf(1);
                }else if(Double.valueOf(String.valueOf(highs6)) >= 5 && Double.valueOf(String.valueOf(highs6)) < 8){
                    score = String.valueOf(2);
                }else{
                    score = String.valueOf(3);
                }
                evaluate = "市场整体行情低迷";
            }else if(Double.valueOf(String.valueOf(highs0)) >= 45 && Double.valueOf(String.valueOf(highs0)) < 60){
                if(Double.valueOf(String.valueOf(highs6)) < 8){
                    score = String.valueOf(4);
                }else if(Double.valueOf(String.valueOf(highs6)) >= 8 && Double.valueOf(String.valueOf(highs6)) < 12){
                    score = String.valueOf(5);
                }else if(Double.valueOf(String.valueOf(highs6)) >= 12 && Double.valueOf(String.valueOf(highs6)) < 15){
                    score = String.valueOf(6);
                }else{
                    score = String.valueOf(7);
                }
                evaluate = "市场整体行情一般";
            }else {
                if(Double.valueOf(String.valueOf(highs6)) < 10){
                    score = String.valueOf(8);
                }else if(Double.valueOf(String.valueOf(highs6)) >= 10 && Double.valueOf(String.valueOf(highs6)) < 15){
                    score = String.valueOf(9);
                }else{
                    score = String.valueOf(10);
                }
                evaluate = "市场整体行情高涨";
            }*/
            CurrentcyHighOrLow entry = new CurrentcyHighOrLow(f10,f10Tof6,f6Tof2,f2To0,z0Toz2,z2Toz4,z4Toz6,z6Toz8,z8Toz10,z10);
            entry.setEvaluate(evaluate);
            entry.setScore(score);
            String createtimeMM = DateUtils.dateFormatString(cmcCurrencyInfos.get(1).getCreateTime(),DateUtils.format_ymdhm);
            //时间保存分钟
            entry.setCreateTime(Integer.valueOf(createtimeMM.substring(createtimeMM.length()-2,createtimeMM.length())));
            entry.setDateTime(DateUtils.dateFormatString(cmcCurrencyInfos.get(1).getCreateTime(),DateUtils.format_ymdhms));
            entry.setAllCount(AllCount);
            entry.setUpCount(count12);
            entry.setDownCount(downCount);
            String jsonstr = JSON.toJSONString(entry);
            LogTrace.info("计算涨跌统计为统计","结果",jsonstr);
            if(StringUtils.isNotBlank(jsonstr)){
                redisServer.set(RedisKeysUtils.TIR_CHANGE_STATISTICS,jsonstr);
            }
           // System.out.println(jsonstr);
            return entry;
        } catch (Exception e) {
            LogTrace.error("涨跌计算统计-百分比数据分类",e);
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 把涨跌统计插入到hbase中
     * @param highOrLow 统计的数据结果
     */
    public void insertHbaseHighsAndLowsCountCalculate(CurrentcyHighOrLow highOrLow){
        //取出当天的数据  判断有没有当天，没有插入当天
        String nowDateStr = DateUtils.dateFormatString(new Date(),DateUtils.format_ymds);
        String nowDateHoursStr = DateUtils.dateFormatString(new Date(),DateUtils.format_ymdh_x);
        String hourStr = nowDateHoursStr.substring(nowDateHoursStr.length()-2,nowDateHoursStr.length());
        try {
            String data = hbaseBaseQueryComponent.selectByQualifierData(HbaseTableUtils.DAILY_CHANGE_STATISTICS_INFO_TABLE_NAME
                    , HbaseTableUtils.DAILY_CHANGE_STATISTICS_INFO_TABLE_FAMILY
                    , HbaseTableUtils.DAILY_CHANGE_STATISTICS_INFO_TABLE_QUALIFIER
                    , nowDateStr);
            String insertStr = "";
           // System.out.println(data);
            List<CurrentcyHighOrLow> curlist = new ArrayList<>();
            if(StringUtils.isBlank(data)){//当天没有值得情况，第一次插入
                Map<String,Object> highsOrlowMap = new HashMap();
                curlist.add(highOrLow);
                highsOrlowMap.put(hourStr,curlist);
                insertStr = JSON.toJSONString(highsOrlowMap);
            }else{
                Map<String,Object> AllDataMap = JSON.parseObject(data);
                //取出小时的数据，判断小时有没有，没有重新插入
                if(AllDataMap.containsKey(hourStr)){
                    List<CurrentcyHighOrLow> oldList = JSON.parseArray(JSON.toJSONString(AllDataMap.get(hourStr)),CurrentcyHighOrLow.class);
                    oldList.add(highOrLow);
                    AllDataMap.put(hourStr,oldList);
                }else {
                    curlist.add(highOrLow);
                    AllDataMap.put(hourStr,curlist);
                }
                insertStr = JSON.toJSONString(AllDataMap);
            }
            currencyInfoHbaseComponent.insertHbaseString(HbaseTableUtils.DAILY_CHANGE_STATISTICS_INFO_TABLE_NAME
                    ,nowDateStr
                    , HbaseTableUtils.DAILY_CHANGE_STATISTICS_INFO_TABLE_FAMILY
                    , HbaseTableUtils.DAILY_CHANGE_STATISTICS_INFO_TABLE_QUALIFIER
                    ,insertStr);
        } catch (HbaseConnectionExcetion | HbaseGetTableExcetion | IOException | HbaseCloseExcetion e) {
            LogTrace.error("涨跌计算统计-hbase插入",e);
            e.printStackTrace();
        }
    }

    /**
     * 计算平台--已经无用
     */
    public Map<String,DailyConceptualIndexInfo> HighsAndLowsCountCalculate() {
         //List<CmcCurrencyInfo> cmcCurrencyInfos
        Map<String,DailyConceptualIndexInfo> result = new HashMap();
        String post = null;
        try {
            List<CmcCurrencyInfo> cmcCurrencyInfos = coinMarketCapDataComponent.ticker("CNY");
            //查询数据库中的平台概念
            List<Map<String,Object>> conceptList = conceptCategoryService.selectAllEnableConceptCategory();
            Map<String,Map<String,Object>> ccM = new HashMap<>();//所有平台下的货币
            //区分平台
            for(Map<String,Object> m :conceptList){
                String cId = (String) m.get("id");
                String cmc_id = (String) m.get("cmc_id");
                Map<String,Object> mz = new HashMap();
                if(ccM.containsKey(cId)){
                    mz =ccM.get(cId);
                    mz.put(cmc_id,cmc_id);
                    ccM.put(cId,mz);
                }else{
                    mz.put(cmc_id,cmc_id);
                    ccM.put(cId,mz);
                }
            }
            //循环时时数据，进行分类
            for(CmcCurrencyInfo info : cmcCurrencyInfos){
                String marketCapCny = info.getMarketCapCny();
                String maketId = info.getId(); //货币名
                for(Map.Entry mInfo :ccM.entrySet()){
                    Map<String,Object> mInfoZ = (Map<String, Object>) mInfo.getValue();
                    if(mInfoZ.containsKey(maketId)){
                        mInfoZ.put(maketId,marketCapCny);
                    }
                }
            }
            Map<String,String> jiashuju = new HashMap();//假数据放基期市值,到时候从reids获取
            Date dateNow = cmcCurrencyInfos.get(0).getCreateTime();//当前获取数据时间
            //分类
            for (Map.Entry resultM:ccM.entrySet()){
                DailyConceptualIndexInfo dailyInfo = new DailyConceptualIndexInfo();
                String GaiKey = (String) resultM.getKey();
                jiashuju.put(GaiKey,"234234278");
                Map<String,Object> resultMZ = (Map<String, Object>) resultM.getValue();
                BigDecimal marketCount = new BigDecimal(0);
                for(Map.Entry marketMap : resultMZ.entrySet()){
                    marketCount.subtract(new BigDecimal(marketMap.getValue().toString()));
                }
                //计算涨幅、概念指数
                BigDecimal jiMarket = new BigDecimal(jiashuju.get(GaiKey));
                BigDecimal market = marketCount.divide(jiMarket).multiply(new BigDecimal("1000"));//概念指数
                market = market.setScale(2,BigDecimal.ROUND_DOWN);
                BigDecimal chang = marketCount.subtract(jiMarket);//涨幅
                chang.multiply(new BigDecimal("100")).setScale(2,BigDecimal.ROUND_DOWN);
                dailyInfo.setCreatetime(dateNow);
                dailyInfo.setConceptChage(chang);
                dailyInfo.setConceptIndex(market);
                result.put(GaiKey,dailyInfo);
                System.out.println(JSON.toJSONString(result));
                return result;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return result;

        }
        return result;
    }

}
